package com.ellecity06.cwhiskymall.ui.webview

import android.content.Intent
import android.net.Uri
import android.webkit.JavascriptInterface
import com.ellecity06.common.helper.LoginHelper
import com.ellecity06.common.ktx.launchActivity
import com.ellecity06.common.ktx.stringResToString
import com.ellecity06.common.utils.CommonUtils.Companion.checkAliPayInstalled
import com.ellecity06.common.utils.CommonUtils.Companion.isInstallAPIK
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.appContext
import com.ellecity06.common.utils.gson
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.bean.web.WechatPayReq
import com.ellecity06.cwhiskymall.helper.PayHelper
import com.ellecity06.cwhiskymall.helper.ShareHelper
import com.ellecity06.cwhiskymall.storage.AppStorage
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.MainActivity
import com.ellecity06.cwhiskymall.ui.mine.auth.AuthNameActivity
import com.ellecity06.cwhiskymall.ui.search.SearchActivity
import com.ellecity06.cwhiskymall.ui.share.poster.SharePosterActivity
import com.ellecity06.cwhiskymall.ui.shop9000.Shop9000Activity
import org.json.JSONObject
import java.lang.ref.WeakReference

/**
 * @author ellecity06
 * @time 2024/11/4 10:02
 * @des
 */
class CommonWebScript(act: WebActivity) {

    private var activity: WeakReference<WebActivity>? = null

    init {
        activity = WeakReference(act)
    }

    /**
     * 跳转首页菜单
     */
    @JavascriptInterface
    fun openTab(tag: String?) {
        logD("h5跳转首页菜单==$tag")

        activity?.get()?.runOnUiThread {
            activity?.get()?.let {
                when (tag) {
                    "home" -> {
                        MainActivity.launch(it, 0)
                    }

                }

            }
        }

    }

    @JavascriptInterface
    fun goRealName() {
        activity?.get()?.runOnUiThread {
            activity?.get()?.launchActivity<AuthNameActivity>()
        }
    }

    /**
     * 关闭h5页面
     */
    @JavascriptInterface
    fun closeWindow() {
        logD("h5做了关闭操作")
        activity?.get()?.runOnUiThread {
            activity?.get()?.finish()
        }

    }

    /**
     * 获取云闪付是否安装
     */
    @JavascriptInterface
    fun getUPPayInstralled(): Int {
        activity?.get()?.let {
            val installAPIK = isInstallAPIK(it, "com.unionpay")
            logD("h5获取云闪付是否安装$installAPIK")
            return if (installAPIK) 1 else 0
        }
        return 0
    }

    /**
     * h5调用的云闪付支付
     * @param tn 交易流水号
     */
    @JavascriptInterface
    fun gotoUPPay(tn: String) {
        logD("tn=$tn")
        activity?.get()?.let {
            it.runOnUiThread {
                PayHelper.uniPay(it, tn)
            }
        }
    }

    /**
     * 分享好友
     */
    @JavascriptInterface
    fun openShare(data: String?) {
        logD("分享好友=${data}")
        activity?.get()?.runOnUiThread {
            if (data != null) {
                val jsonObject = JSONObject(data)
                val id = jsonObject.getInt("id")
                activity?.get()?.launchActivity<SharePosterActivity>(Pair("good_id", id))
            }
        }

    }

    /**
     * 打开搜索页
     */
    @JavascriptInterface
    fun openSearch() {
        activity?.get()?.runOnUiThread {
            activity?.get()?.launchActivity<SearchActivity>()
        }

        logD("h5打开搜索页")
    }

    /**
     * 给前端传递token
     */
    @JavascriptInterface
    fun getToken(): String? {
        logD("h5页面主动获取token")
        return AppStorage.token
    }

    /**
     * 跳转到微信小程序 支付
     */
    @JavascriptInterface
    fun goToWechatAppletPay2(url: String, name: String) {
        logD("h5调起微信支付url=${url},name=${name}")
        activity?.get()?.runOnUiThread {
            ShareHelper.goWeChatApplet(url, name)
        }
    }

    /**
     * 显示标题栏
     */
    @JavascriptInterface
    fun showTitle(title: String) {
        logD("h5调起显示标题=${title}")
        activity?.get()?.runOnUiThread {
            activity?.get()?.showTitle(title)
        }
    }

    /**
     * 显示标题栏
     */
    @JavascriptInterface
    fun hideTitle() {
        logD("h5调起隐藏标题")
        activity?.get()?.runOnUiThread {
            activity?.get()?.hideTitle()
        }

    }

    /**
     * 跳转到登录页
     */
    @JavascriptInterface
    fun openLogin() {
        activity?.get()?.runOnUiThread {
            activity?.get()?.let {
                LoginHelper.instance.logout(it)
            }
        }
    }

    /**
     * 跳转到酒神专区打卡领取贡献金页面
     */
    @JavascriptInterface
    fun openDionysusZone() {
        activity?.get()?.runOnUiThread {
            activity?.get()?.let {
                it.launchActivity<Shop9000Activity>()
            }
        }
    }

    /**
     * 打开商品详情
     */
    @JavascriptInterface
    fun openGoods(id: Int) {
        activity?.get()?.runOnUiThread {
            activity?.get()?.let {
                WebHelper.goodDetails(it, id)
            }
        }
    }

    /**
     * 打开新的页面
     */
    @JavascriptInterface
    fun openNewPage(url: String, title: String) {
        logD("打开新的页面=url=${url},title=${title}")
        activity?.get()?.runOnUiThread {
            WebActivity.launch(activity?.get()!!, url = url, title = title, needToken = false)
        }

    }

    /**
     * 调用支付宝
     * 相当于打开一个支付网页
     */
    @JavascriptInterface
    fun goToAlipayUrl(payUrl: String) {
        if (!checkAliPayInstalled(appContext)) {
            ToastUtils.show(R.string.text_please_install_zfb.stringResToString())
            return
        }
        val scheme = "alipays://platformapi/startapp?saId=10000007&qrcode=${payUrl}"
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(scheme))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

        activity?.get()?.startActivityForResult(intent, WebActivity.REQUEST_ALIPAY_CODE)
    }

    /**
     * 判断是否拥有邀请人
     */
    @JavascriptInterface
    fun hasUpShareCode(): Int {
        return if (UserStorage.isHasUp()) 1 else 0
    }

    @JavascriptInterface
    fun goToWechatPay(data: String?) {
        logD("h5调起原生支付=$data")
        if (!data.isNullOrEmpty()) {
            try {
                activity?.get()?.runOnUiThread {
                    val webPayReq = gson.fromJson(data, WechatPayReq::class.java)
                    PayHelper.wechatPay(webPayReq)
                }

            } catch (e: Exception) {
                logD("", tr = e)
            }


        }
    }
}